package com.lin.netty.improve.粘包与半包;

import com.lin.netty.utils.ByteBufUtils;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Slf4j
public class Server4 {

    public static void main(String[] args) {
        new ServerBootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(16, 16, 16)) // 设置netty的接收缓冲区(byteBuf),这是针对每个通道的设置
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();

                        // maxFrameLength 最大帧长度，如果消息超过了maxFrameLength会报错TooLongFrameException
                        pipeline.addLast("lengthDecoder", new LengthFieldBasedFrameDecoder(1024, 0, 4, 0, 4));
                        pipeline.addLast("log", new LoggingHandler()); // 日志，打印入站出站日志

                        pipeline.addLast("in1", new SimpleChannelInboundHandler<ByteBuf>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
                                byte[] bytes = new byte[msg.readableBytes()];
                                msg.readBytes(bytes);
                                log.debug("收到数据：{}", new String(bytes));
                            }
                        });
                    }
                })
                .bind(1122);
    }
}
